package com.test.demo.Util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 获取本机端口号+ip
 * @author zx
 */
@Component
public class IpConfigurationUtils implements ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;
    @Value("${server.port}")
    public  String port;

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

    public int getPort() {
        return Integer.parseInt(this.port);
    }

    public String getHostAddress(){
        try {
            InetAddress address = InetAddress.getLocalHost();
           return address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }

    public String getHostAndPort(){
        return getHostAddress()+":"+getPort();
    }

}
